<template>
  <div class="bg-background-900">
    <!-- 认证状态检查 -->
    <div v-if="userStore.loading" class="min-h-screen flex items-center justify-center">
      <LoadingSpinner />
    </div>
    
    <!-- 主要内容 -->
    <div v-else>
      <!-- 全宽轮播图横幅 -->
      <div class="w-full">
        <LoadingSpinner v-if="isInitialLoading" />
        <div v-else>
          <MovieCarousel :movies="carouselMovies" />
        </div>
      </div>
      
      <!-- 其他内容区域 -->
      <div class="max-w-6xl mx-auto px-4">
        <div class="mt-8">
          <HotMoviesRow :movies="hotMovies" />
        </div>
        <div class="mt-8">
          <MovieMasonry :initial-movies="masonryMovies" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useUiStore } from '../store/useUiStore'
import { useLoadingStore } from '../store/useLoadingStore'
import { useUserStore } from '../store/useUserStore'
import { storeToRefs } from 'pinia'
import { LoadingSpinner } from '../components/ui'
import MovieCarousel from '../components/movie/MovieCarousel.vue'
import HotMoviesRow from '../components/movie/HotMoviesRow.vue'
import MovieMasonry from '../components/movie/MovieMasonry.vue'
import { useMovieLoader } from '../composables/movies'

const uiStore = useUiStore()
const loadingStore = useLoadingStore()
const userStore = useUserStore()
const { currentColumns } = storeToRefs(uiStore)
const { batchLoadMovies } = useMovieLoader()

// 响应式数据
const isInitialLoading = ref(true)
const carouselMovies = ref<any[]>([])
const hotMovies = ref<any[]>([])
const masonryMovies = ref<any[]>([])
const hasLoadedContent = ref(false)

// 计算需要加载的电影数量
const hotMoviesCount = computed(() => currentColumns.value * 2)
const masonryMoviesCount = computed(() => currentColumns.value * 2) // 修改为加载两行的数据

// 批量加载所有电影数据
const loadAllMovies = async () => {
  if (hasLoadedContent.value) return // 避免重复加载
  
  const startTime = performance.now()
  isInitialLoading.value = true
  loadingStore.startLoading('加载首页数据...')
  
  try {
    console.log('开始加载首页数据...')
    
    const requests = [
      { type: 'carousel' as const, count: 4, offset: 0 },
      { type: 'hot' as const, count: hotMoviesCount.value, offset: 0 },
      { type: 'masonry' as const, count: masonryMoviesCount.value, offset: 0 }
    ]

    console.log('批量加载请求:', requests)
    const results = await batchLoadMovies(requests)
    console.log('批量加载完成:', results)
    
    // 分配结果到各个组件
    carouselMovies.value = results.get('carousel_4_0') || []
    hotMovies.value = results.get(`hot_${hotMoviesCount.value}_0`) || []
    masonryMovies.value = results.get(`masonry_${masonryMoviesCount.value}_0`) || []
    
    // 调试：检查轮播图数据
    console.log('Carousel movies:', carouselMovies.value)
    if (carouselMovies.value.length > 0) {
      console.log('First carousel movie:', carouselMovies.value[0])
      console.log('First carousel movie description:', carouselMovies.value[0]?.description)
    }
    
    // 调试：检查瀑布流数据
    console.log('Masonry movies count:', masonryMovies.value.length)
    console.log('Masonry movies:', masonryMovies.value)
    console.log('Masonry movies IDs:', masonryMovies.value.map(m => m.id))
    console.log('Hot movies count:', hotMovies.value.length)
    console.log('Hot movies:', hotMovies.value)
    console.log('Current columns:', currentColumns.value)
    console.log('Masonry movies count computed:', masonryMoviesCount.value)
    
    const loadTime = performance.now() - startTime
    console.log(`首页加载完成，耗时: ${loadTime.toFixed(2)}ms`)
    
    hasLoadedContent.value = true
  } catch (error) {
    console.error('Error loading movies:', error)
  } finally {
    isInitialLoading.value = false
    loadingStore.stopLoading()
  }
}

// 监听列数变化，重新加载热门和瀑布流电影
const reloadMoviesOnColumnChange = async () => {
  if (isInitialLoading.value) return
  
  try {
    const requests = [
      { type: 'hot' as const, count: hotMoviesCount.value, offset: 0 },
      { type: 'masonry' as const, count: masonryMoviesCount.value, offset: 0 }
    ]

    const results = await batchLoadMovies(requests)
    
    hotMovies.value = results.get(`hot_${hotMoviesCount.value}_0`) || []
    masonryMovies.value = results.get(`masonry_${masonryMoviesCount.value}_0`) || []
    
  } catch (error) {
    console.error('Error reloading movies:', error)
  }
}

// 监听认证状态变化
watch(() => userStore.loading, (newLoading) => {
  if (!newLoading && !hasLoadedContent.value) {
    // 认证状态确定后，开始加载内容
    loadAllMovies()
  }
}, { immediate: true })

onMounted(async () => {
  // 如果认证状态已经确定且还没有加载内容，则加载内容
  if (!userStore.loading && !hasLoadedContent.value) {
    await loadAllMovies()
  }
})

// 监听列数变化
watch(currentColumns, () => {
  reloadMoviesOnColumnChange()
})
</script>
